package com.example.adtest

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.wifi.WifiManager
import android.os.Build
import android.util.Log
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.URL
import javax.net.ssl.HttpsURLConnection

object NetworkUtils {
    private const val TAG = "NetworkUtils"
    private const val IP_API_URL = "https://api.ipify.org?format=json"
    private const val IP_INFO_URL = "https://ipinfo.io/json"

    /**
     * 获取内网IP地址
     */
    fun getLocalIpAddress(context: Context): String? {
        try {
            // 首先尝试通过WifiManager获取
            val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            if (wifiManager.isWifiEnabled) {
                val wifiInfo = wifiManager.connectionInfo
                val ipInt = wifiInfo.ipAddress
                val ip = String.format(
                    "%d.%d.%d.%d",
                    (ipInt and 0xFF),
                    (ipInt shr 8 and 0xFF),
                    (ipInt shr 16 and 0xFF),
                    (ipInt shr 24 and 0xFF)
                )
                return ip
            }

            // 如果Wifi未开启，通过NetworkInterface获取
            val en = NetworkInterface.getNetworkInterfaces()
            while (en.hasMoreElements()) {
                val networkInterface = en.nextElement()
                val enu = networkInterface.inetAddresses
                while (enu.hasMoreElements()) {
                    val inetAddress = enu.nextElement()
                    if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                        return inetAddress.hostAddress
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取内网IP失败: ${e.message}")
        }
        return null
    }

    /**
     * 获取公网IP地址
     */
    fun getPublicIpAddress(): String? {
        try {
            val url = URL(IP_API_URL)
            val connection = url.openConnection() as HttpsURLConnection
            connection.connectTimeout = 5000
            connection.readTimeout = 5000
            connection.requestMethod = "GET"

            val responseCode = connection.responseCode
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = StringBuilder()
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    response.append(line)
                }
                reader.close()

                // 解析JSON响应
                val jsonResponse = response.toString()
                if (jsonResponse.contains("ip")) {
                    val ipStart = jsonResponse.indexOf("ip") + 5
                    val ipEnd = jsonResponse.indexOf("\"", ipStart)
                    return jsonResponse.substring(ipStart, ipEnd)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取公网IP失败: ${e.message}")
        }
        return null
    }

    /**
     * 获取IP信息（地区和运营商）
     * 返回Pair<地区, 运营商>
     */
    fun getIpInfo(): Pair<String, String>? {
        try {
            val url = URL(IP_INFO_URL)
            val connection = url.openConnection() as HttpsURLConnection
            connection.connectTimeout = 5000
            connection.readTimeout = 5000
            connection.requestMethod = "GET"

            val responseCode = connection.responseCode
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = StringBuilder()
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    response.append(line)
                }
                reader.close()

                val jsonResponse = response.toString()
                Log.d(TAG, "IP信息响应: $jsonResponse")

                // 解析地区信息
                var region = "未知"
                if (jsonResponse.contains("region")) {
                    val regionStart = jsonResponse.indexOf("region") + 9
                    val regionEnd = jsonResponse.indexOf("\"", regionStart)
                    if (regionStart < regionEnd) {
                        region = jsonResponse.substring(regionStart, regionEnd)
                    }
                }

                // 解析运营商信息
                var org = "未知"
                if (jsonResponse.contains("org")) {
                    val orgStart = jsonResponse.indexOf("org") + 6
                    val orgEnd = jsonResponse.indexOf("\"", orgStart)
                    if (orgStart < orgEnd) {
                        org = jsonResponse.substring(orgStart, orgEnd)
                        // 提取运营商名称
                        if (org.contains("China Telecom")) {
                            org = "电信"
                        } else if (org.contains("China Mobile")) {
                            org = "移动"
                        } else if (org.contains("China Unicom")) {
                            org = "联通"
                        } else {
                            // 如果无法识别，保留原始信息
                            org = org.substringBeforeLast(
                                ' ', 
                                "未知"
                            )
                        }
                    }
                }

                return Pair(region, org)
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取IP信息失败: ${e.message}")
        }
        return null
    }

    /**
     * 检查网络连接状态
     */
    fun isNetworkConnected(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork ?: return false
            val networkCapabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
            return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        } else {
            @Suppress("DEPRECATION")
            val networkInfo = connectivityManager.activeNetworkInfo
            return networkInfo != null && networkInfo.isConnected
        }
    }
}